import React from "react";
import { RouteComponentProps, withRouter } from "react-router-dom";

class AsyncComponent extends React.Component<IAsyncComponentProps> {
  private unmount = false;

  state = {
    component: null,
  };

  render() {
    const c = this.state.component;
    if (c == null) {
      return <>loading</>;
    }
    const CC = (c["default"] ? c["default"] : c[Object.keys(c)[0]]) as any;
    this.props.onLoaded?.();
    return <CC {...this.props} />;
  }

  async componentDidMount() {
    // UI.showLoading()
    this.props.beforeLoad?.();
    const pageName = this.props.match.params.pageName;
    const c = await this.props.importFunc(pageName).catch((e) => {
      console.error(`异步组件加载失败，可能是路径错误，或者是不存在该文件`, e);
    });
    if (!this.unmount) {
      this.setState({
        component: c,
      });
    }
  }

  componentWillUnmount() {
    this.unmount = true;
  }
}

export default withRouter(AsyncComponent);

export interface IAsyncComponentProps
  extends RouteComponentProps<IMainmenuRouteParams>,
    IAsyncPageLoadProps {
  /**动态 import 的模块，例如：()=>import("./page/folder/module")*/
  match?: any;
  importFunc: (pageName: string) => Promise<any>;
  /**页面加载完成事件 */
  onLoaded?: () => void;
}

export interface IMainmenuRouteParams {
  pageName: string;
}

export interface IAsyncPageLoadProps {
  /**异步组件加载前触发 */
  beforeLoad?: () => void;
}
